<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/10/10
 * Time: 下午4:16
 */

namespace Lm\Controllers;


use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\user\XhsysUser;
use Helpers\Assets;
use Helpers\Main;
use Helpers\Template;
use Helpers\UserPower;
use Admin\Models\lm\XHLmUseMR;

class MRoomController extends ControllerBase
{

    public function indexAction()
    {
        echo 'meeting Room';
    }


    private static $enums = [
        'iState' => [1 => '等待办公室审批', 2 => '审批通过', 3 => '撤销申请']
    ];

    public function notFoundAction()
    {
        return $this->response->setStatusCode(404)->setJsonContent(['code' => 404, 'error' => 'page not found!']);
    }

    /**
     * 使用会议室列表
     *
     * created by dale 2017/10/10
     */
    public function useMRListAction()
    {
        UserPower::checkUserPower('Lm_MR_UseMRList') or die('缺少权限');
        Assets::easyUI();
        Assets::importJs('js/mroom/useMRList.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/myTool.js');
        $this->view->pick('mroom/useMRList');

        Template::exists('useMRList', 'list') or die(Main::showMessageModal('useMRList 配置文件不存在，请先创建！', 109106002));
        $listButton = $listSearchArr = [];
        if (UserPower::checkUserPower('Lm_MR_UseMRList_Add')) {
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '申请会议室', 'icon' => 'fa-plus');
        }
        if (UserPower::checkUserPower('Lm_MR_UseMRList_Del')) {
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除申请', 'icon' => 'fa-trash');
        }
        $listButton[] = array('plain' => 'true', 'id' => 'bt_list_undo', 'text' => '撤销申请', 'icon' => 'fa-undo');
        $enums = self::$enums;
        $enums['iState'][''] = '请选择';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_state', 'data' => $enums['iState'],
                                 'default' => '');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search',
                                 'style' => 'margin-left:10px');
        $this->view->setVars(array(
            'useMRList' => Template::createList('useMRList', 'useMRList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButton),
            ]),
            'editable' => UserPower::checkUserPower('Lm_MR_UseMRList_Edit'),
        ));
    }

    /**
     * 申请会议室表单
     *
     * created by dale 2017/10/10
     */
    public function useMRFormAction()
    {
        $id = $this->request->getQuery('iUMRId', 'string');
        if (isset($id)) {
            UserPower::checkUserPower('Lm_MR_UseMRList_Edit') or die('缺少权限');
        } else {
            UserPower::checkUserPower('Lm_MR_UseMRList_Add') or die('缺少权限');
        }
        $this->view->pick('mroom/useMRForm');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/mroom/useMRForm.js');
        Assets::datetimePicker();
        Assets::easyUI();
        Assets::sweetAlert2();
        $userId = Main::getLoginUserInfo('userId');
        if (isset($id)) {
            $mr             = XHLmUseMR::findFirst([
                'conditions' => 'bDelete=0 AND iUMRId=:iUMRId:',
                'bind'       => ['iUMRId' => $id],
            ])->toArray();
            $mr['sDepName'] = XhhrmDepart::getDepEnum()[$mr['iDepId']];
            if ($mr['iState'] == 1) {
                $flag = !is_bool(strpos($this->changeToId(Main::getConfigByName('lm')['sOfficeCharges']), strval($userId)));
                if ($flag) {
                    $mr['iState'] = 2;
                    $checkStr     = '';
                } else {
                    $checkStr = "parent.$('#bt_modal_confirm').hide();";
                }

            } else {
                $checkStr = "parent.$('#bt_modal_confirm').hide();";
            }
            $mrInfo = json_encode($mr);
        } else {
            $mrInfo   = '1';
            $checkStr = "";
        }


        $staff = XhhrmStaff::findFirst([
            'conditions' => 'bDelete=0 AND iUserId=:iUserId:',
            'bind'       => ['iUserId' => $userId],
        ]);
        if ($staff) {
            $staff = $staff->toArray();
        } else {
            $checkStr            = "parent.$('#bt_modal_confirm').hide();";
            $staff['sStaffName'] = '账号未绑定';
            $iPDepId             = '';
            $sDepName            = '';
        }
        $iPDepId  = end(array_filter(explode(',', $staff['sDepIds'])));
        $sDepName = XhhrmDepart::getDepEnum()[$iPDepId];
        $this->view->setVars([
            'mrInfo'       => $mrInfo,
            'userName'     => $staff['sStaffName'],
            'iDepId'       => $iPDepId,
            'sDepName'     => $sDepName,
            'iMeetingRoom' => XhsysEnum::getEnumByNodeName('会议室'),
            'check'        => $checkStr,
        ]);
    }


    public function getUseMRAction()
    {
        UserPower::checkUserPower('Lm_MR_UseMRList') or die('缺少权限');
        $key = $this->request->getPost('key', 'string');
        $state = $this->request->getPost('state', 'string');
        $builder = $this->modelsManager->createBuilder()
            ->columns('mr.*')
            ->from(['mr' => 'Admin\Models\lm\XHLmUseMR'])
            ->where('mr.bDelete=0');

        $userId = Main::getLoginUserInfo('userId');
        $flag   = !is_bool(strpos($this->changeToId(Main::getConfigByName('lm')['sOfficeCharges']), strval($userId)));
        if (!UserPower::checkUserPower('Lm_MR_UseMRList_All')) {
            if ($flag) {//办公室的人,可以看到自己创建的,并且所有状态等待办公室审批的
                $builder->andWhere('mr.iCreateUserId=:iUserId: OR mr.iState=1 ', array('iUserId' => $userId));
            } else { //不是办公室的,只能看见自己创建的
                $builder->andWhere('mr.iCreateUserId=:iUserId: ', array('iUserId' => $userId));
            }
        }
        if ($key) {
            $builder->andWhere('mr.sApplyName like :key:', array('key' => '%' . $key . '%'));
        }
        if ($state) {
            $builder->andWhere('mr.iState = :state:', array('state' => $state));
        }

        $data = Main::runBuilderPaginator($builder, true);
        $enums = self::$enums;
        $enums['iMeetingRoom'] = XhsysEnum::getEnumByNodeName('会议室');
        foreach ($data['rows'] as $index => $row) {
            $data['rows'][$index]['iState'] = $enums['iState'][$row['iState']];
            $data['rows'][$index]['iMeetingRoom'] = $enums['iMeetingRoom'][$row['iMeetingRoom']];
        }
        Main::runUserNameById($data['rows'], ['iLastModifyUserId' => 'iLastModifyUserId'], true);
        return $this->sendJsonResponse($data);
    }

    /**
     * 保存申请
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/10/10
     */
    public function saveUseMRAction()
    {
        $id = $this->request->getPost('iUMRId', 'string');

        if ($id != "") {
            UserPower::checkUserPower('Lm_MR_UseMRList_Edit') or die('缺少权限');
            $obj = XHLmUseMR::findFirst([
                'conditions' => 'bDelete=0 AND iUMRId=:iUMRId:',
                'bind'       => ['iUMRId' => $id]
            ]);
        } else {
            UserPower::checkUserPower('Lm_MR_UseMRList_Add') or die('缺少权限');
            $obj = new XHLmUseMR();
        }
        $obj->assign($this->request->getPost());
        if ($obj->save()) {
            return $this->sendSuccessResponse('发起申请成功');
        } else {
            return $this->sendSuccessResponse(500, '发起申请失败');
        }
    }


    /**
     * 删除申请
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/10/10
     */
    public function delUseMRAction()
    {
        UserPower::checkUserPower('Lm_MR_UseMRList_Del') or die('缺少权限');
        $ids = $this->request->getPost('ids', 'string') or die('缺少参数');
        $ids    = explode(',', $ids);
        $mrs    = XHLmUseMR::find([
            'conditions' => 'bDelete=0 AND iUMRId in ({ids:array})',
            'bind'       => ['ids' => $ids]
        ]);
        $userId = Main::getLoginUserInfo('userId');
        $flag   = !is_bool(strpos($this->changeToId(Main::getConfigByName('lm')['sOfficeCharges']), strval($userId)));
        foreach ($mrs as $mr) {
            $mr->bDelete = 1;
            if ($mr->iState == 1 && $flag) {
                if (!$mr->save()) {
                    return $this->sendErrorResponse(500, '车辆申请记录删除失败');
                }
            } else {
                if ($mr->iState == 2) {
                    return $this->sendErrorResponse(500, '已经审批通过');
                } else {
                    return $this->sendErrorResponse(500, '没有权限');
                }
            }
            if (!$mr->save()) {
                return $this->sendErrorResponse(500, '车辆申请记录删除失败');
            }
        }

        return $this->sendSuccessResponse('车辆申请记录删除成功');
    }


    public function undoUseMRAction()
    {
        $id = $this->request->getPost('id', 'string') or die('缺少参数');
        $mr     = XHLmUseMR::findFirst([
            'conditions' => 'bDelete=0 AND iUMRId = :id:',
            'bind'       => ['id' => $id]
        ]);
        $userId = Main::getLoginUserInfo('userId');
        if ($userId == $mr->iCreateUserId) {
            if ($mr->iState == 2) {
                return $this->sendSuccessResponse('已审批通过无法撤销');
            }
            $mr->iState = 3;
            if ($mr->save()) {
                return $this->sendSuccessResponse('撤销成功');
            } else {
                return $this->sendErrorResponse(500, '撤销失败');
            }
        } else {
            return $this->sendErrorResponse(500, '没有权限');
        }
    }

    public function changeToId($str)
    {
//        $str='xjqdale,xjdale';
        $str   = explode(',', $str);
        $users = XhsysUser::find([
            'columns'    => 'iUserId',
            'conditions' => 'bDelete=0 AND sLogonName in ({ids:array})',
            'bind'       => ['ids' => $str]
        ])->toArray();
        $users = implode(',', array_column($users, 'iUserId'));
        return $users;
    }

    public function mrEnumAction()
    {
        $tStartTime = $this->request->getPost('startTime') or die('缺少参数 startTime');
        $mrEnum = XhsysEnum::getEnumByNodeName('会议室');
        $useMRs = XHLmUseMR::find([
            'columns'    => 'iMeetingRoom',
            'conditions' => 'tStartTime <= :nowTime: AND tEndTime >= :nowTime:',
            'bind'       => ['nowTime' => $tStartTime],
        ]);
        foreach ($useMRs as $index => $obj) {
            unset($mrEnum[$obj->iMeetingRoom]);
        }
        return json_encode($mrEnum);
    }

    /**
     * 会议室列表
     * created by dale 2017/10/17
     */
    public function mrListAction()
    {
        Assets::easyUI();
        Assets::importJs('js/mroom/mrList.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/myTool.js');
        $this->view->pick('mroom/mrList');
        $this->view->setVars(array(
            'mrList' => Template::createList('mrList', 'mrList', [
//                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
//                'buttonToolbar' => Template::createButtonToolBar($listButton),
            ]),
//            'editable'=>UserPower::checkUserPower('Lm_MR_useMRList_Edit'),
        ));
    }
}
